from django import forms
from core.models import Notification, ClassTaskTodo
from django.contrib.auth import get_user_model

User = get_user_model()

class NotificationForm(forms.ModelForm):
    """通知表单，用于创建和发送通知"""
    task = forms.ModelChoiceField(
        queryset=ClassTaskTodo.objects.all(),
        required=False,
        empty_label="-- 不关联待办事务 --",
        widget=forms.Select(attrs={'class': 'form-select'}),
        label="关联待办事务"
    )

    class Meta:
        model = Notification
        fields = ['title', 'content', 'receiver', 'task']
        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '输入通知标题'}),
            'content': forms.Textarea(attrs={'class': 'form-control', 'rows': 4, 'placeholder': '输入通知内容'}),
            'receiver': forms.Select(attrs={'class': 'form-select'}),
        }
        labels = {
            'title': '通知标题',
            'content': '通知内容',
            'receiver': '接收者',
        }

    def __init__(self, *args, **kwargs):
        self.sender = kwargs.pop('sender', None)
        super().__init__(*args, **kwargs)

        # 根据发送者角色过滤接收者
        if self.sender:
            # 获取发送者角色
            from core.models import UserRoleAssignment
            sender_roles = UserRoleAssignment.objects.filter(user=self.sender).values_list('role__name', flat=True)

            # 校长可以发送给年级组长
            if 'principal' in sender_roles:
                receivers = UserRoleAssignment.objects.filter(role__name='grade_leader').values_list('user_id', flat=True)
            # 年级组长可以发送给班主任
            elif 'grade_leader' in sender_roles:
                receivers = UserRoleAssignment.objects.filter(role__name='homeroom_teacher').values_list('user_id', flat=True)
            # 班主任可以发送给班级学生
            elif 'homeroom_teacher' in sender_roles:
                from core.models import StudentClassRelationship
                class_ids = StudentClassRelationship.objects.filter(teacher=self.sender).values_list('class_id', flat=True)
                receivers = StudentClassRelationship.objects.filter(class_id__in=class_ids).exclude(teacher=self.sender).values_list('student_id', flat=True)
            else:
                receivers = []

            self.fields['receiver'].queryset = User.objects.filter(id__in=receivers)
            self.fields['receiver'].empty_label = None

    def save(self, commit=True):
        instance = super().save(commit=False)
        if self.sender:
            instance.sender = self.sender
        if commit:
            instance.save()
        return instance